package com.umakr.ax.security.core.handler;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author gx
 * @since 2017/5/15
 */
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private static final String ACCEPT_CONTAINS = "application/json";

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        String accept = request.getHeader("accept");
        // ajax 登录
        if(accept != null && accept.contains(ACCEPT_CONTAINS)){
            Map<String,Object> objectMap  = Maps.newHashMap();
            objectMap.put("result",1);
            response.getWriter().write(JSON.toJSONString(objectMap));
        }else{
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}
